package com.ruoyi.extdata.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.extdata.common.ExtReqEnum;
import com.ruoyi.extdata.common.OnepipeTripleDES;
import com.ruoyi.extdata.common.config.OnepipeConfig;
import com.ruoyi.extdata.domain.OkRequestVo;
import com.ruoyi.extdata.service.*;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OnepipeServiceImpl implements IOnePipeService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private OnepipeConfig onepipeConfig;

    @Value("${server.run-env}")
    private String environment;

    @Autowired
    private IExternalApiService iExternalApiService;

    public static final String ONE_PIPE_INCR_NO = "one_pipe:incr_no_";

    @Override
    public JSONObject lookupAccount(String accountNumber, String bankCode,String userId) throws Exception {

        String toBeEncryted = accountNumber + ";" + bankCode;
        String secure = OnepipeTripleDES.encrypt(toBeEncryted, onepipeConfig.getSecretKey());


        String dateTime = DateUtils.dateTime();
        String serialNo = environment + dateTime +  redisCache.increment(ONE_PIPE_INCR_NO, 1L);
        String signature = Hex.encodeHexString(DigestUtils.getMd5Digest().digest((serialNo + ";" + onepipeConfig.getSecretKey()).getBytes()));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("request_ref", serialNo);
        jsonObject.put("request_type", "lookup_account_mid");
        JSONObject auth = new JSONObject();
        auth.put("type", "bank.account");
        auth.put("secure", secure);
        auth.put("auth_provider", onepipeConfig.getAuthProvider());
        jsonObject.put("auth", auth);
        JSONObject transaction = new JSONObject();
        transaction.put("transaction_ref", serialNo);
        transaction.put("transaction_desc", "kyc");
        JSONObject customer = new JSONObject();
        customer.put("customer_ref", serialNo);
        transaction.put("customer", customer);
        jsonObject.put("transaction", transaction);
        return request(signature, jsonObject,userId);
    }

    public JSONObject request(String signature, JSONObject params,String userId) throws Exception {

        String apiUrl = onepipeConfig.getBaseUrl();
        Headers.Builder headersBuilder = new Headers.Builder();
        headersBuilder.add("Content-Type", "application/json");
        headersBuilder.add("Authorization", "Bearer " + onepipeConfig.getApiKey());
        headersBuilder.add("Signature", signature);
        Headers headers = headersBuilder.build();
        OkRequestVo post = OkRequestVo.builder().apiName("Lookup-Account-Mid").url(apiUrl).reqMethod("POST").params(params).reqEnum(ExtReqEnum.JSON).headers(headers).build();
        post.setUserId(userId);
        JSONObject resultJson = iExternalApiService.crsRequest(post);
        if ("Failed".equals(resultJson.get("status").toString())) {
            log.error("OnePipe，请求异常，{}", resultJson);
            return null;
        }
        return resultJson;

    }

}
